<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.sheetheader_add" @click="handleAddBtn()">新 增 </el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.sheetheader_delete" @click="handleDelete('sheetDel')" :disabled="!deleteLeft"
          >删 除
        </el-button>
        <el-button type="primary" size="small" icon="el-icon-refresh" v-if="permission.sheetheader_synchro" @click="handleSync">同 步 </el-button>
      </template>
      <template slot-scope="{ row }" slot="status">
        <span>{{ row.status | filterStatus }}</span>
      </template>
      <template slot-scope="{ row }" slot="generationType">
        <span>{{ row.generationType == 'ERP' ? 'ERP同步' : 'MES新增' }}</span>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          type="text"
          icon="el-icon-view"
          size="small"
          plain
          v-if="permission.sheetheader_view"
          style="border: 0; background-color: transparent !important"
          @click.stop="handleView(row)"
          >详情
        </el-button>
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          plain
          :disabled="row.generationType == 'ERP' || row.status == 0"
          v-if="row.sheetType !== 'SCRAP' && permission.sheetheader_edit"
          style="border: 0; background-color: transparent !important"
          @click.stop="handleEdit(row)"
          >编辑
        </el-button>
        <el-button
          type="text"
          size="small"
          icon="el-icon-delete"
          plain
          :disabled="row.status == 0 || row.status == 2"
          v-if="row.sheetType !== 'SCRAP' && permission.sheetheader_delete"
          style="border: 0; background-color: transparent !important"
          @click="rowDel(row)"
          >删 除
        </el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :close-on-click-modal="false" :title="title" :visible.sync="showDialog" v-if="showDialog" width="60%" top="7vh">
      <avue-form ref="type" v-model="typeObj" :option="typeOption" v-if="title === '新增'"></avue-form>
      <avue-form ref="properties" v-model="properties" :option="propertiesOption"></avue-form>
      <!-- <h4 v-if="typeObj.sheetType === 'RO'">BOM物料信息</h4> -->
      <avue-crud
        :option="sheetOption"
        :table-loading="detailLoading"
        :data="sheetData"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="sheetForm"
        ref="addTableCrud"
        :key="timer"
        @selection-change="selectionDetailChange"
      >
        <!-- <template slot-scope="{ row }" slot="scrapType">
          <span>{{ row.scrapType === 'P-SCRAP' ? '产品报废' : '维修报废' }}</span>
        </template> -->
        <template slot-scope="{ row }" slot="menu">
          <el-button type="text" icon="el-icon-view" size="small" plain style="border: 0; background-color: transparent !important" @click.stop="viewPackIdDetail(row)"
            >包装详情
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addSheetDetail()" v-if="deleteFlag" :disabled="status == 2">新 增 </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="deleteFlag" @click="handleDetailDelete(typeObj.sheetType)" :disabled="status == 2"
            >删 除
          </el-button>
        </template>
      </avue-crud>
      <!-- <h4 v-if="typeObj.sheetType === 'RO'">替代料</h4>
      <avue-crud
        v-if="typeObj.sheetType === 'RO'"
        :option="sheetOption"
        :table-loading="detailLoading"
        :data="replacePartData"
        :permission="permissionList"
        :before-open="beforeOpen"
        ref="replaceTableCrud"
      ></avue-crud> -->
      <span slot="footer" class="dialog-footer" :style="{ display: isNone }">
        <el-button type="primary" size="small" :icon="title == '新增' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'" @click="submit" v-preventReClick>{{
          title == '新增' ? '保 存' : '修 改'
        }}</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="reset">取 消</el-button>
      </span>
      <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    </el-dialog>
    <el-dialog append-to-body :close-on-click-modal="false" title="包装信息" :visible.sync="showPackIdDialog" width="60%" top="7vh">
      <avue-crud :option="packIdOption" :table-loading="packIdLoading" :data="packIdData" :permission="permissionList">
        <template slot-scope="{ row }" slot="status">
          <span>{{ row.status | filterPackStatus }}</span>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, getSheetDetail, getPackId, getReplacePart } from '@/api/warehouse/sheetheader';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import {
  getOption,
  getPoColumn,
  getRoColumn,
  getBsColumn,
  getPoTableColumn,
  getRoTableColumn,
  getBsTableColumn,
  getMoTableColumn,
  getFoTableColumn,
  getScrapTableColumn,
  getTypeOption,
  getPackIdOption
} from './sheetheader';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'SHEETH_HEADER',
      poCol: getPoColumn(this),
      bsCol: getBsColumn(this),
      roCol: getRoColumn(this),
      poTableCol: getPoTableColumn(this),
      roTableCol: getRoTableColumn(),
      moTableCol: getMoTableColumn(),
      foTableCol: getFoTableColumn(),
      bsTableCol: getBsTableColumn(this),
      scrapTableCol: getScrapTableColumn(),
      typeOption: getTypeOption(this),
      packIdOption: getPackIdOption(),
      option: getOption(),
      sourceType: '',
      sheetSubType: '',
      form: {},
      typeObj: {},
      sheetTypeName: '',
      sheetType: '', //采购单类型
      sheetForm: {},
      properties: {},
      timer: new Date().getTime(),
      loading: false,
      detailLoading: false,
      packIdLoading: false,
      isNone: '', //是否显示修改
      title: '',
      receiveRecordNumber: '', //有无收料记录
      tableOption: [], //模态框配置
      isAllowAdd: true,
      status: -1,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      rowData: {}, //行数据
      selectionList: [],
      selectionDetailList: [],
      showDialog: false,
      showPackIdDialog: false,
      data: [],
      sheetData: [],
      packIdData: [],
      replacePartData: [],
      propertiesOption: {
        //单据FORM配置
        labelWidth: '110',
        submitBtn: false,
        emptyBtn: false,
        column: []
      },
      sheetOption: {
        //单据CRUD配置
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        dialogClickModal: false,
        height: '400',
        border: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        cancelBtn: false,
        saveBtn: false,
        selection: true,
        menu: false,
        page: false,
        index: true,
        indexLabel: '序号',
        refreshBtn: false,
        expandBtn: false,
        column: []
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.sheetheader_add, false),
        viewBtn: this.vaildData(this.permission.sheetheader_view, false),
        delBtn: this.vaildData(this.permission.sheetheader_delete, false),
        editBtn: this.vaildData(this.permission.sheetheader_edit, false)
      };
    },
    deleteFlag() {
      switch (this.typeObj.sheetType) {
        case 'RO':
          return false;
        case 'BS':
          return false;
        case 'PO':
        case 'MO':
        case 'FO':
          let flag = !(this.title === '查看');
          return flag;
        case 'SCRAP':
          return false;
        default:
          return true;
      }
    },
    deleteLeft() {
      if (this.selectionList.length !== 0) {
        return this.selectionList.every((item, index) => {
          return item.status === 1;
        });
      }
      return true;
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  filters: {
    filterStatus(status) {
      switch (status) {
        case 0:
          return '已完成';
        case 1:
          return '未完成';
        case 2:
          return '进行中';
      }
    },
    filterPackStatus(status) {
      switch (status) {
        case 1:
          return '待入库';
        case 2:
          return '已锁定';
        case 3:
          return '部分锁定';
        case 4:
          return '已报废';
        case 5:
          return '已出库';
        case 6:
          return '已入库';
        default:
          break;
      }
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    async rowDel(row) {
      if (this.typeObj.sheetType === 'PO') {
        const data = await getList(1, 1, { sheetNo: row.sheetNo }, 'PO');
        const data2 = data.data;
        let reslut = data2.code == 200 ? data2.data.records[0] : {};
        if (reslut.status == 2) {
          this.$message({
            type: 'warning',
            message: `采购单${row.sheetNo}正在进行中，无法进行删除`
          });
          return;
        }
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    async handleDelete(titleCrud) {
      for (let i = 0; i < this.selectionList.length; i++) {
        if (this.selectionList[i].sheetType === 'PO') {
          let data = await getDetail(this.selectionList[i].id);
          let reslut = data.data.data[0];
          if (reslut.status == 2) {
            this.$message({
              type: 'warning',
              message: `当前选项中采购单${reslut.sheetNo}正在进行中，无法进行删除`
            });
            return;
          }
          return;
        }
      }

      if (titleCrud == 'sheetDel') {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.crud.toggleSelection();
          });
      }
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.sheetTypeStrList = 'PO,FO,RO,BS,SCRAP';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handlePrint() {
      this.$refs.crud.rowPrint();
    },
    handleSync() {},
    reset() {
      this.showDialog = false;
    },
    handleDetailDelete(type) {
      if (this.selectionDetailList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      switch (type) {
        case 'PO':
          this.sheetData = this._differenceBy(this.sheetData, this.selectionDetailList, 'partMasterCode');
          break;
        case 'FO':
          this.sheetData = this._differenceBy(this.sheetData, this.selectionDetailList, 'sourceNo');
          break;
        case 'MO':
          this.sheetData = this._differenceBy(this.sheetData, this.selectionDetailList, 'id');
          break;
        default:
          break;
      }
    },
    ransferToNumber(inputNumber) {
      if (isNaN(inputNumber) || !inputNumber) {
        return inputNumber;
      }
      inputNumber = '' + inputNumber;
      inputNumber = parseFloat(inputNumber);
      let eformat = inputNumber.toExponential(); // 转换为标准的科学计数法形式（字符串）
      let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/); // 分离出小数值和指数值
      let number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]));
      return number;
    },
    /**
     * 去除对象value为空的属性
     */
    clearObjAttr(item) {
      let keys = [];
      this._forEach(item, (value, key) => {
        if (!value) {
          keys.push(key);
        }
      });
      if (this.title === '新增') {
        keys.push('id');
      }
      return this._omit(item, keys);
    },
    /*
     * 提交
     */
    submit() {
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          this.$refs.addTableCrud.validateCellForm().then((res) => {
            let obj = res || {};
            if (Object.keys(obj).length === 0) {
              if (this.typeObj.sheetType === 'BS') {
                let result = this.sheetData.every((item, index) => {
                  if (!item.quantity) {
                    item.quantity = 0;
                  }
                  return item.quantity <= item.requisitionQuantity - item.completedQuantity;
                });
                if (!result) {
                  this.$message.warning('退货数量不能大于领料数量');
                  return;
                }
              }

              if (this.typeObj.sheetType === 'RO') {
                let result = this.sheetData.every((item, index) => {
                  if (!item.quantity) {
                    item.quantity = 0;
                  }
                  return item.quantity <= item.workOrderRequireQuantity - item.completedQuantity;
                });
                if (!result) {
                  this.$message.warning('领用数量不能大于工单数量');
                  return;
                }
              }

              if (this.judgeSheetLotRepeat(this.sheetData) && this.typeObj.sheetType === 'PO') {
                this.$message.warning('采购单行号重复，请检查并修改!');
                return;
              }

              let params = {
                sourceType: this.sourceType,
                sheetSubType: this.sheetSubType, //GENERAL
                bomId: this.properties.bomId,
                sourceNo: this.properties.sourceNo,
                originalSheetId: this.properties.id,
                originalSheetNo: this.properties.sheetNo,
                sheetType: this.typeObj.sheetType,
                sheetDate: this.properties.sheetDate,
                partnerId: this.properties.partnerId,
                partnerName: this.properties.partnerName,
                partnerCode: this.properties.partnerCode,
                description: this.properties.description,
                principal: this.properties.principal,
                sourceId: this.properties.sourceId
              };
              // if(this.typeObj.sheetType === 'BS' ){
              //   params.sourceType = 'STORE_REQUISITION';
              // }else if(this.typeObj.sheetType === 'RO'){
              //   params.sourceType = 'WORKORDER'
              // }
              let sheetDetails = this._map(this.sheetData.concat(this.replacePartData), (item) => {
                // if(this.typeObj.sheetType !== 'BS'){
                //   item.sourceId = this.properties.sourceId;
                // }
                return this.clearObjAttr(item);
              });

              if (this.title !== '新增') {
                params['status'] = this.properties.status;
                params['id'] = this.properties.sheetId;
              }
              add({
                ...this.clearObjAttr(params),
                sheetDetails
              }).then(
                (res) => {
                  let data = res.data.data;
                  this.$message({
                    type: 'success',
                    message: `${data.sheetNo}${this.sheetTypeName}${this.title === '新增' ? '创建' : '编辑'}成功!`
                  });
                  done();
                  this.showDialog = false;
                  this.refreshChange();
                },
                (error) => {
                  window.console.log(error);
                }
              );
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /**
     * 添加单据详情打开相应模态框
     */
    addSheetDetail() {
      let type = this.typeObj.sheetType;
      switch (type) {
        case 'PO':
          this.openPartModal();
          break;
        case 'MO':
          this.openReceiveCommonModal();
          break;
        case 'FO':
          this.openFQCInspectionCommonModal();
          break;
        default:
          break;
      }
    },
    /**
     * 新增模态框
     */
    handleAddBtn() {
      this.title = '新增';
      this.isNone = 'inline';
      this.typeObj.sheetType = 'PO';
      this.addDis('PO');
      this.status = -1;
      this.showDialog = true;
    },
    /**
     * 查看模态框
     */
    handleView(row) {
      this.title = '详情';
      this.isNone = 'none';
      this.$set(this.typeObj, 'sheetType', row.sheetType);
      this.viewDis(row.sheetType);
      this.judgeType(row.sheetType);
      this.showDialog = true;
      this.resetForm();
      this.editAndViewFn(row);
    },
    /**
     * 编辑模态框
     */
    handleEdit(row) {
      this.title = '编辑';
      this.isNone = 'inline';
      this.$set(this.typeObj, 'sheetType', row.sheetType);
      this.receiveRecordNumber = row.receiveRecordNumber;
      this.status = row.status;
      this.editDis(row.sheetType);
      this.judgeType(row.sheetType);
      this.showDialog = true;
      this.resetForm();
      this.editAndViewFn(row);
    },

    /**
     * 编辑和查看
     */
    async editAndViewFn(row) {
      this.properties.sheetId = row.id;
      let type = row.sheetType;
      const id = row.id;
      switch (type) {
        case 'PO':
          this.addPoForm(row);
          this.getListData(id);
          break;
        case 'MO':
        case 'FO':
          this.getListData(id);
          break;
        case 'RO':
          this.properties.sourceId = row.sourceId;
          this.properties.status = row.status;
          this.addRoForm(row);
          this.getListData(id);
          // let data = await getReplacePart({ bomId: row.bomId, sourceNo: row.sourceNo });
          // this.addReplacePart(data.data.data);
          break;
        case 'BS':
          this.getListData(id);
          this.addBsForm(row);
          break;
        case 'SCRAP':
          this.getListData(id);
          break;
        default:
          break;
      }
    },
    /**
     * 获取单据详情 PO MO FO RO
     */
    getListData(id) {
      this.sheetData = [];
      this.detailLoading = true;
      const type = this.typeObj.sheetType;
      getDetail(id).then((res) => {
        const data = res.data.data;
        switch (type) {
          case 'PO':
            this.addPo(data);
            break;
          case 'MO':
            this._forEach(data, (item) => {
              item.sheetNo = item.sourceNo;
            });
            this.addMo(data);
            break;
          case 'FO':
            this.addFo(data);
            break;
          case 'RO':
            this._forEach(data, (item) => {
              item.sourceId = item.id;
            });
            this.addRo(data);
            break;
          case 'BS':
            this.properties.sourceId = id;
            this._forEach(data, (item) => {
              if (this.title === '新增') {
                item.quantity = '';
                item.returnQuantity = '';
                item.requisitionQuantity = 0;
                item.requisitionQuantity = item.completedQuantity;
              }
              item.sourceId = item.id;
            });
            this.addBs(data);
            break;
          case 'SCRAP':
            this.addScrap(data);
          default:
            break;
        }
        this.detailLoading = false;
      });
    },

    /**
     * 选择模态框数据
     */
    async getSelectedRows(rowData, titleInfo) {
      const type = this.typeObj.sheetType;
      let flag;
      switch (type) {
        case 'PO':
          if (titleInfo !== 'partnerInfo') {
            flag = this.isRepeatPart(this.sheetData, rowData, 'partMasterCode', 'partNo');
            if (!flag) {
              return;
            }
            let data = this._map(rowData, (item) => {
              item['partMasterId'] = item.id;
              item['receiveQuantity'] = '';
              return this._omit(item, ['id']);
            });
            this.addPo(data);
          } else {
            this.addPartner(rowData);
          }
          break;
        case 'RO':
          this.detailLoading = true;
          // this.getCrudMenuClass('RO');
          let data = await getSheetDetail({ bomId: rowData.bomId, sourceNo: rowData.orderNo });
          let data2 = data.data.data;
          this.addRoForm(rowData);
          this.properties.sourceId = rowData.id;
          this._forEach(data2, (item) => {
            item.quantity = '';
            item.returnQuantity = '';
            item.sourceId = item.id;
          });
          this.addRo(data2);
          // let data2 = await getReplacePart({ bomId: rowData.bomId, sourceNo: rowData.orderNo });
          // this.addReplacePart(data2.data.data);
          this.detailLoading = false;
          break;
        case 'FO':
          flag = this.isRepeatPart(this.sheetData, rowData, 'documentNo', 'documentNo');
          if (!flag) {
            return;
          }
          // this._forEach(rowData, (item) => {
          //   item.sourceNo = item.sheetNo;
          // })
          // console.log(rowData, 5555555555)
          this.addFo(rowData);
          break;
        case 'MO':
          flag = this.isRepeatPart(this.sheetData, rowData, 'id', 'id');
          if (!flag) {
            return;
          }
          this._forEach(rowData, (item) => {
            item.sourceNo = item.sheetNo;
          });
          this.addMo(rowData);
          break;
        case 'BS':
          this.properties.sourceId = rowData.id;
          this.properties.sourceNo = rowData.sourceNo;
          this.addBsForm(rowData);
          this.getListData(rowData.id);
          break;
        default:
          this.addPartner(rowData);
          break;
      }
    },

    /**
     * 判断物料数据是否有相同
     */
    isRepeatPart(arr1, arr2, attr1, attr2) {
      let flag = this._some(arr1, (item1) => {
        return this._some(arr2, (item2) => {
          return item1[attr1] === item2[attr2];
        });
      });

      if (flag) {
        this.$message({
          type: 'warning',
          message: '选择的物料与已选的物料有重复,请重新选择'
        });
        return false;
      }
      return true;
    },

    /**
     * 添加供应商信息
     */
    addPartner(row) {
      this.$set(this.properties, 'partnerName', row.name);
      this.$set(this.properties, 'partnerCode', row.partnerNo);
      this.$set(this.properties, 'partnerId', row.id);
      this.$set(this.properties, 'principal', row.principal);
    },

    /**
     * 获取采购单表单
     */
    addPoForm(row) {
      this.properties['partnerName'] = row.partnerName;
      this.properties['partnerId'] = row.partnerId;
      this.properties['sheetDate'] = row.sheetDate;
      this.properties['status'] = String(row.status);
      this.properties['sheetId'] = row.id;
    },

    /**
     * 添加领料单表单
     */
    addRoForm(row) {
      // if (this.typeObj.sheetType === 'RO' && this.title === '新增') {
      //   this.properties.sourceId = row.id;
      // }
      this.properties.status = row.status;
      this.$set(this.properties, 'sourceNo', row.orderNo || row.sourceNo);
      this.$set(this.properties, 'partNo', row.partNo || row.productNo);
      this.$set(this.properties, 'partName', row.partName || row.productName);
      this.$set(this.properties, 'bomVersion', this._get(row, 'bomVersion', ''));
      this.$set(this.properties, 'planQuantity', this._get(row, 'workOrderRequireQuantity', '') || this._get(row, 'planQuantity', ''));
      this.$set(this.properties, 'bomId', this._get(row, 'bomId', ''));
    },

    /**
     * 添加退料单表单
     */
    addBsForm(row) {
      // if (this.typeObj.sheetType === 'BS' && this.title === '新增') {
      //   this.properties.sourceId = row.id;
      // }
      this.$set(this.properties, 'status', row.status);
      this.$set(this.properties, 'sheetNo', row.sheetNo);
      this.$set(this.properties, 'sourceNo', row.sourceNo);
      this.$set(this.properties, 'bomId', row.bomId);
      this.$set(this.properties, 'id', row.id);
      this.$set(this.properties, 'description', this._get(row, 'description', ''));
    },

    /**
     * 添加退料单数据
     */
    // async getBsDetail(id) {
    //   this.detailLoading = true;
    //   let data = await getDetail(id);
    //   let data2 = data.data.data;
    //   this._forEach(data2, (item) => {
    //       item.quantity = '';
    //       item.returnQuantity = '';
    //       item.requisitionQuantity = item.completedQuantity;
    //       item.sourceId = item.id;
    //   })
    //   this.addBs(data2)
    //   this.detailLoading = false;
    // },

    /**
     * 替代料数据
     */
    addReplacePart(data) {
      this.replacePartData = this.getTableData(data);
    },

    /**
     * 添加领料单数据
     */
    addRo(data) {
      this.sheetTypeName = '领料单';
      this.sourceType = 'WORKORDER';
      this.sheetSubType = '';
      this.sheetData = this.getTableData(data);
    },

    /**
     * 添加成品入库单
     */
    addFo(data) {
      this.sheetTypeName = '成品入库单';
      this.sourceType = '';
      this.sheetSubType = '';
      this.addTableData(data);
    },

    /**
     * 添加原材料单
     */
    addMo(data) {
      this.sourceType = '';
      this.sheetSubType = '';
      this.addTableData(data);
    },

    /**
     * 添加采购单
     */
    addPo(data) {
      this.sheetTypeName = '采购单';
      this.sourceType = '';
      this.sheetSubType = 'GENERAL';
      this.addTableData(data);
    },

    /**
     * 添加退料单
     */
    addBs(data) {
      this.sheetTypeName = '退料单';
      this.sourceType = 'STORE_REQUISITION';
      this.sheetSubType = '';
      this.sheetData = this.getTableData(data);
      // console.log(this.getTableData(data),)
    },

    /**
     * 添加报废入库单
     */
    addScrap(data) {
      this.sourceType = '';
      this.sheetSubType = '';
      this.sheetData = this._map(data, (item) => {
        return {
          productSequenceNumber: item.productSequenceNumber,
          partMasterCode: item.partMasterCode,
          partMasterName: item.partMasterName,
          partMasterModel: item.partMasterModel,
          quantity: item.quantity,
          scrapType: item.scrapType,
          scrapHandleBy: item.scrapHandleBy,
          scrapHandleTime: item.scrapHandleTime
        };
      });
    },

    /**
     * 获取单据物料数据 RO BS
     */
    getTableData(data) {
      return this._map(data, (item, index) => {
        return {
          id: item.id,
          sheetLot: item.sheetLot,
          partMasterId: item.partMasterId,
          partMasterName: item.partMasterName || item.partName,
          partMasterCode: item.partMasterCode || item.partNo,
          partMasterModel: item.partMasterModel || item.partModel,
          quantity: item.quantity,
          unitQty: item.unitQty,
          categoryName: item.categoryName || item.partCategoryName,
          completedQuantity: this.title === '新增' ? 0 : this.ransferToNumber(item.completedQuantity || 0),
          requisitionQuantity: item.requisitionQuantity || 0,
          receivingQuantity: this._get(item, 'receivingQuantity', '') || 0,
          workOrderRequireQuantity: this._get(item, 'workOrderRequireQuantity', '') || 0,
          returnQuantity: this._get(item, 'returnQuantity', '') || 0,
          sourceNo: item.sourceNo,
          sourceId: item.sourceId,
          sourceType: this.sourceType,
          $cellEdit: true
        };
      });
    },
    /**
     * 添加单据物料数据 PO MO FO
     */
    addTableData(data) {
      this.sourceType = '';
      let tempArr = [];
      for (let i = 0; i < data.length; i++) {
        let item = {
          id: data[i].id,
          sheetLot: this._get(data[i], 'sheetLot', ''),
          lotNo: this._get(data[i], 'lotNo', ''),
          partMasterName: this._get(data[i], 'name', '') || this._get(data[i], 'partMasterName', '') || this._get(data[i], 'partName', ''),
          partMasterCode: this._get(data[i], 'partNo', '') || this._get(data[i], 'partMasterCode', ''),
          partMasterModel: this._get(data[i], 'partModel', '') || this._get(data[i], 'partMasterModel', ''),
          partMasterId: this._get(data[i], 'partMasterId', '') || this._get(data[i], 'partId', ''),
          partType: this._get(data[i], 'partType', ''),
          sheetNo: this._get(data[i], 'sheetNo', ''),
          quantity:
            this._get(data[i], 'quantity', '') ||
            this._get(data[i], 'planQuantity', '') ||
            this._get(data[i], 'receiveQuantity', '') ||
            this._get(data[i], 'sendExamineQuantity', ''),
          sourceNo: this._get(data[i], 'orderNo', '') || this._get(data[i], 'sourceNo', ''),
          documentNo: this._get(data[i], 'documentNo', ''),
          completedQuantity: this._get(data[i], 'completedQuantity', '') || 0,
          sourceId: this._get(data[i], 'sourceId', ''),
          $cellEdit: true
        };
        tempArr.push(item);
      }
      this.sheetData = this._orderBy(
        this.sheetData.concat(tempArr).map((item, idx) => {
          if (this.typeObj.sheetType === 'PO' && this.title === '新增') {
            item.sheetLot = idx + 1;
          }
          return item;
        }),
        ['sheetLot'],
        ['asc']
      );
    },
    /**
     * 查看包装条码详情
     */
    async viewPackIdDetail(row) {
      this.showPackIdDialog = true;
      this.packIdLoading = true;
      let data = await getPackId({ partMasterId: row.partMasterId, sheetId: this.properties.sheetId, sheetDetailId: row.id });
      this.packIdData = data.data.data;
      this.packIdLoading = false;
    },

    //数据重置
    resetForm() {
      this.$nextTick(() => {
        this.$refs.properties.resetForm();
      });
    },
    //判断单行号是否重复
    judgeSheetLotRepeat(data) {
      let len = data.length;
      for (let i = 0; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
          if (data[i].sheetLot == data[j].sheetLot) {
            return true;
          }
        }
      }
      return false;
    },
    /**
     * 样式切换
     */
    getCrudMenuClass(type) {
      let cssStr = '';
      if (type === 'RO') {
        cssStr = 'display: none!important';
      } else {
        cssStr = 'display: flex!important';
      }
      this.$nextTick(() => {
        let dom = document.querySelectorAll('.el-dialog__body  .avue-crud .avue-crud__menu');
        dom.forEach((el) => {
          el.style.cssText = cssStr;
        });
      });
    },

    /**
     * 单据类型切换
     */
    judgeType(type) {
      this.timer = new Date().getTime();
      this.propertiesOption.column = [];
      this.sheetData = [];
      if (this.title === '新增') {
        this.resetForm();
      }
      // this.$nextTick(() => {
      //   this.getCrudMenuClass(type);
      // });
      switch (type) {
        case 'PO': //采购单
          this.propertiesOption.column = this.poCol;
          this.sheetOption.column = this.poTableCol;
          this.$nextTick(() => {
            if (this.title === '新增') {
              this.$set(this.properties, 'sheetDate', this.$moment().format('yyyy-MM-DD HH:mm:ss'));
            }
          });
          break;
        case 'RO': //领料单
          this.replacePartData = [];
          this.propertiesOption.column = this.roCol;
          this.sheetOption.column = this.roTableCol;
          break;
        case 'MO': //原材料入库单
          this.sheetOption.column = this.moTableCol;
          break;
        case 'FO': //成品入库单
          this.sheetOption.column = this.foTableCol;
          break;
        case 'BS': //退料
          this.sheetOption.column = this.bsTableCol;
          this.propertiesOption.column = this.bsCol;
          break;
        case 'SCRAP': //报废入库单
          this.typeObj.sheetType = type;
          this.sheetOption.column = this.scrapTableCol;
          break;
        default:
          this.sheetOption.column = [];
          break;
      }
    },
    /**
     * 供应商信息模态框
     */
    openPartnerModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        titleInfo: 'partnerInfo',
        columnDefs: [
          // {
          //   label: '类型',
          //   prop: 'partnerType',
          //   type: 'select',
          //   dicUrl: '/api/blade-system/dict-biz/dictionary?code=partner_type',
          //   props: {
          //     label: 'dictValue',
          //     value: 'dictKey'
          //   }
          // },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '缩写',
            prop: 'abbreviation'
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '位置',
            prop: 'locations'
          }
        ]
      };
    },

    /**
     * 工单信息模态框
     */
    openWorkOrderModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: `选择生产工单信息（双击进行选择）`,
        url: '/api/mes-product/work-order/page?markField=1',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        titleInfo: 'workInfo',
        // filterOption: {
        //   isFilter: true,
        //   prop: 'id',
        //   data: this.sheetData.map((item) => item.id)
        // },
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            rules: [
              {
                required: true,
                message: '请选择工单类型',
                trigger: 'change'
              }
            ],
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName',
            search: true
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          }
        ]
      };
    },

    /**
     * FQC检验单模态框
     */
    openFQCInspectionCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: 'FQC检验信息',
        url: `/api/mes-product/inspection-document/documentPage?documentType=FQC&status=2&examineResult=OK`,
        isPage: true,
        index: false,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '工单号',
            search: true,
            searchOrder: 2,
            prop: 'sourceNo'
          },
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            searchOrder: 1
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true,
            searchOrder: 3
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '产品规格',
            prop: 'partModel'
          },
          {
            label: '报检数量',
            prop: 'sendExamineQuantity'
          }
        ]
      };
    },

    /**
     * 领料单信息模态框
     */
    openRoSheetCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择领料单信息（双击进行选择）',
        url: `/api/mes-warehouse/sheetheader/page?sheetType=RO`,
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '领料单',
            prop: 'sheetNo',
            search: true,
            minWidth: 150
          },
          {
            label: '工单',
            prop: 'sourceNo',
            search: true,
            minWidth: 150
          }
        ]
      };
    },

    /**
     * 收料记录信息模态框page
     */
    openReceiveCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择单据信息',
        url: `/api/mes-warehouse/receiving/page?inspectionMode=EXEMPTION&examineResult=OK`,
        isPage: true,
        index: false,
        rowSelectionType: 'multiple',
        // filterOption: {
        //   isFilter: true,

        //   prop: 'id',
        //   data: this.sheetData.map((item) => item.id)
        // },
        columnDefs: [
          {
            label: '采购单号',
            prop: 'sheetNo',
            search: true,
            searchOrder: 2
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true,
            searchOrder: 4
          },
          {
            label: '物料名称',
            prop: 'partName',
            searchOrder: 5
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '物料批次',
            prop: 'lotNo'
          },
          {
            label: '实收数量',
            prop: 'receiveQuantity'
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          {
            label: '供应商编码',
            prop: 'vendorCode'
          },
          {
            label: '收料日期',
            prop: 'receiveDate'
          }
        ]
      };
    },

    /**
     * 打开物料信息模态框
     */
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料信息',
        url: '/api/mes-admin/part-master/page?partType=MATERIAL',
        // filterOption: {
        //   isFilter: true,
        //   prop: 'partNo',
        //   data: this.sheetData.map((item) => item.partMasterCode)
        // },
        index: false,
        isPage: true,
        rowSelectionType: '',
        titleInfo: 'partInfo',
        columnDefs: [
          {
            label: '物料类型',
            prop: 'categoryId',
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料型号',
            prop: 'partModel'
          }
        ]
      };
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 查看有无收料记录表单启用禁用
     */
    receiveRecord(val) {
      switch (val) {
        case 0:
          this.poCol[0].disabled = false;
          this.poCol[1].disabled = false;
          // this.poCol[2].disabled = false;
          if (this.status == 2) {
            this.poCol[0].disabled = true;
            this.poTableCol[0].disabled = true;
            this.poTableCol[4].disabled = true;
          }
          break;
        default:
          this.poCol[0].disabled = true;
          this.poCol[1].disabled = false;
          // this.poCol[2].disabled = true;
          if (this.status == 2) {
            this.poCol[0].disabled = true;
            this.poTableCol[0].disabled = true;
            this.poTableCol[4].disabled = true;
          }
          break;
      }
      // if (val) {
      //   this.poCol[0].disabled = true;
      //   this.poCol[1].disabled = false;
      //   // this.poCol[2].disabled = true;
      //   this.poTableCol[4].disabled = false;
      // } else {
      //   this.poCol[0].disabled = false;
      //   this.poCol[1].disabled = false;
      //   // this.poCol[2].disabled = false;
      //   this.poTableCol[4].disabled = false;
      // }
    },
    /**
     * 查看启用禁用
     */
    viewDis(type) {
      switch (type) {
        case 'PO':
          this.poCol[0].disabled = true;
          this.poCol[1].disabled = true;
          // this.poCol[2].readonly = false;
          // this.poCol[2].disabled = true;
          this.poTableCol[0].disabled = true;
          this.poTableCol[4].disabled = true;
          this.poTableCol[5].hide = false;
          this.sheetOption.menu = false;
          this.sheetOption.index = false;
          // this.sheetOption.height = 400;
          break;
        case 'BS':
          // this.bsCol[0].disabled = true;
          this.bsCol[2].disabled = true;
          this.bsTableCol[5].disabled = true;
          this.sheetOption.menu = false;
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'RO':
          // this.roCol[0].disabled = true;
          // this.roCol[0].readonly = false;
          this.roTableCol[7].disabled = true;
          this.sheetOption.menu = false;
          this.sheetOption.index = true;
          // this.sheetOption.height = 200;
          break;
        case 'MO':
          this.sheetOption.menu = true;
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'FO':
          this.sheetOption.menu = true;
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'SCRAP':
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        default:
          break;
      }
    },
    /**
     * 编辑禁用
     */
    editDis(type) {
      this.sheetOption.menu = false;
      switch (type) {
        case 'BS':
          // this.bsCol[0].disabled = false;
          this.bsCol[2].disabled = false;
          this.bsTableCol[5].disabled = false;
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'RO':
          // this.roCol[0].readonly = true;
          // this.roCol[0].disabled = false;
          this.roTableCol[7].disabled = false;
          this.sheetOption.index = true;
          // this.sheetOption.height = 200;
          break;
        case 'PO':
          this.poCol[1].display = true;
          // this.poCol[2].disabled = true;
          this.poTableCol[0].disabled = false;
          this.poTableCol[5].hide = true;
          this.sheetOption.index = false;
          this.poTableCol[4].disabled = false;
          // this.sheetOption.height = 400;
          this.receiveRecord(this.receiveRecordNumber);
          break;
        case 'MO':
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'FO':
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        default:
          break;
      }
    },
    /**
     * 添加禁用
     */
    addDis(type) {
      this.sheetOption.menu = false;
      switch (type) {
        case 'BS':
          // this.bsCol[0].disabled = false;
          this.bsCol[2].disabled = false;
          this.bsTableCol[5].disabled = false;
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'RO':
          // this.roCol[0].readonly = true;
          // this.roCol[0].disabled = false;
          this.roTableCol[7].disabled = false;
          this.sheetOption.index = true;
          // this.sheetOption.height = 200;
          break;
        case 'PO':
          this.poCol[1].display = false;
          // this.poCol[2].disabled = true;
          this.poTableCol[0].disabled = false;
          this.poTableCol[5].hide = true;
          this.sheetOption.index = false;
          this.poTableCol[4].disabled = false;
          // this.sheetOption.height = 400;
          this.receiveRecord(this.receiveRecordNumber);
          break;
        case 'MO':
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        case 'FO':
          this.sheetOption.index = true;
          // this.sheetOption.height = 400;
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .avue-form__group .avue-form__menu.avue-form__menu--center {
  display: none;
}
</style>
